package com.hyjx.framework.service.session;

import com.hyjx.framework.common.Constants;
import com.hyjx.framework.service.SystemService;
import oracle.jdbc.driver.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis 无状态session 实现类
 */
@Component("redisSession")
public final class SessionRedis implements ISession {
	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 读取Session
	 *
	 * @param key
	 * @return
	 */
	@Override
	public Object get(final String key) {
		String userId = SystemService.getJSessionId();
		if ("".equals(userId)) {
			return null;
		}

		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
		return operations.get(userId + "." + key);
	}

	/**
	 * 读取session
	 *
	 * @param key
	 * @return
	 */
	@Override
	public String getString(String key) {
		Object obj = get(key);
		if (obj != null) {
			return (String) obj;
		} else {
			return null;
		}
	}

	@Override
	public void invalidate() {
		remove(Constants.USERINFO);
	}

	@Override
	public void forceSet(String key, Object value) {
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入Session
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	@Override
	public void set(String key, Object value) {
		set(key, value, 18000L);
	}

	public void setByRequest(HttpServletRequest request, String key, Object value) {
		set(key,value);
	}

	/**
	 * 写入Session
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	private boolean set(final String key, Object value, Long expireTime) {
		String userId = SystemService.getJSessionId();
		if ("".equals(userId)) {
			return false;
		}

		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(userId + "." + key, value);
			redisTemplate.expire(userId + "." + key, expireTime, TimeUnit.SECONDS);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public void setRedisTemplate(
			RedisTemplate<Serializable, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	/**
	 * 删除对应的value
	 *
	 * @param key
	 */
	@Override
	public void remove(final String key) {
		String userId = SystemService.getJSessionId();
		if ("".equals(userId)) {
			return;
		}

		if (exists(userId+"."+key)) {
			redisTemplate.delete(userId+"."+key);
		}
	}

	/**
	 * 判断Session中是否有对应的value
	 *
	 * @param key
	 * @return
	 */
	public boolean exists(final String key) {
		return redisTemplate.hasKey(key);
	}
}